package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    //点击确认提交之后收集的地址和商品和token信息
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = new OrderConfirmVo();

        //拿到thread_local中的共享用户的信息，
        //这个拦截器通过session拿到之后共享了，优雅
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        System.out.println("main"+Thread.currentThread().getId());
        //拿到请求头，放入另外两个子线程,RequestContextHolder也是一个threadlocal，子线程拿不到RequestContextHolder中的数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //RequestContextHolder.setRequestAttributes(requestAttributes);
//        List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
//        confirmVo.setAddress(address);
//
//        //RequestContextHolder.setRequestAttributes(requestAttributes);
//        List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
//        confirmVo.setItems(items);

        //使用异步+threadLocal会导致子线程拿不到ThreadLocal中共享的数据，因为ThreadLocal是线程安全的
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //查收获地址，子线程给自己存一份cookie
            System.out.println("member"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            System.out.println(address);
            confirmVo.setAddress(address);
        },executor);

        CompletableFuture<Void> itemsFuture = CompletableFuture.runAsync(() -> {
            //这里让feign 远程调用 cartFeignService自动获取用户id,会丢失请求头；而通过网页发送的时候，
            //feign远程调用会创建一个新的request，相当于自己拿java代码再发一个请求，请求头里什么都没有
            //所以购物车服务就认为没有登陆
            //必须加上feign的远程调用的请求拦截器
            //而网页发一定会携带session中的内容，不会丢失
            //获取选中购物享
            System.out.println("cart"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            System.out.println(items);
            confirmVo.setItems(items);
            //上面confirmVo已经接收到了商品信息，直接从confirmVo中拿就是了
        },executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId())
                    .collect(Collectors.toList()); //拿到所有的商品的ID
            R skuHasStock = wareFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = skuHasStock.getData(new TypeReference<List<SkuStockVo>>() {});
            if (data != null) {
                Map<Long, Boolean> booleanMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(booleanMap);
            }
        },executor);

        //查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //一定要加上get(),不加就不会等待，直接返回null

        System.out.println(confirmVo.toString());
        //订单总额和应付金额自动计算
        //防重令牌 防止用户提交订单点击多次，一个订单下了多个订单，
        //这样即使用户点击多次，最终提交的也只是一个购物车中的一个订单
        //点击购物车结算生成一个订单的的时候生成，就生成一个token，预先先用UUID生成一个token，USER_ORDER_TOKEN, redis中存一份，前端存一份
        //提交订单去支付的时候验证token，使用redis+lua脚本实现，保证了验证token和删除token的原子性，验证和删除必须同时进行，
        //在第一个请求过来的时候验证token通过后就删掉token，这样，就算同时点击多次，也只会生成一个订单
        String token = UUID.randomUUID().toString().replace("-", "");
        //redis中存一份
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        //前端存一份，提交订单的时候进行验证
        confirmVo.setOrderToken(token);

        //get容易导致阻塞，一般放到程序后面，不干扰其他任务的执行
        //get只有等到结果才向下执行，因此，异步的时候放到最后，执行时间就是get的最大时长
        //不妨最后，后面的执行还要耗费时间
        CompletableFuture.allOf(addressFuture,itemsFuture).get();

        return confirmVo;
    }

    //确认提交后的
    //本地事务的缺点
    //1、只能控制本地事务的回滚，若某个服务出现异常，已经执行的远程事务将无法回滚
    // 如 若优惠券系统出现问题，订单会回滚，而锁库存将不能回滚，

    //2、由于网络问题导致的假失败问题
    // 锁库存系统执行成功，但是因为远程调用超时问题出现异常，订单回滚

    //因此需要用到分布式事务
    //@GlobalTransactional   //高并发seata不适用

    /**
     * 分布式事务的几种方案
     * 1、2PC,使用seata实现，使用了很多锁，高并发场景下不适用
     * 2、TCC 柔性事务 TCC 补偿方案，允许在一定时间内，不同节点的数据库不一致，但要求最终一致
     * 3、柔性事务 最大努力通知方案
     * 4、柔性事务 可靠消息+最终一致性（异步确保型）
     * @param vo
     * @return
     */

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {

        //用户提交来的信息共享
        //包括addrId，orderToken,payPrice,payType等等
        orderSubmitVoThreadLocal.set(vo);

        //提交要返回的响应结果
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();

        //拿到当前登陆的用户信息
        //loginUser中的值来自于登陆页面共享的session，包含所有当前的用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        response.setCode(0);

        //原子验证和删除lua脚本
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

        //下单来到支付选择页面
        //下单：创建订单，验证令牌，验证价格，锁库存
        //1、验证令牌[令牌的对和删除必须包装原子性，不然就可能出现同时多个订单同时进来]
        String orderToken = vo.getOrderToken();
        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());

        //OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()
        //redis.call('get',KEYS[1]) 查到在redis里面保存的token
        //orderToken = vo.getOrderToken();  orderToken是用户发过来的token
        //redisTemplate.execute 执行lua脚本
        //1、Lua脚本原子令牌验证 验证成功和删除 要保证原子性
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if(result==0L){
            //1、token验证失败
            response.setCode(1);
            return response;
        }else{
            //1、验证原子令牌成功
            response.setCode(0);
            //下单：创建订单，验证令牌，验证价格，锁库存
            //创建好一个总的订单，addr信息通过传来的addrId查到，
            //获取购物车里的选中商品通过用户的共享session里的用户id查到
            OrderCreateTo order = createOrder();
            //验价,小于0.01就是对比成功的
            BigDecimal payPrice = vo.getPayPrice(); //前端发来的,价格是自动计算出来的
            BigDecimal payAmount = order.getOrder().getPayAmount(); //后端计算出来的

            //2、验证价格,验价成功
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01) {
                //对比成功
                //3、保存订单,将订单的数据保存到数据库
                saveOrder(order);

                //4、锁库存,只有有异常就回滚数据，
                //订单号，所有订单项（skuId,skuName,num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //有异常返回R.error(code,msg)

                //1、为了保证高并发，可以发消息给库存服务，让库存服务自己回滚
                //2、库存服务也可以使用自动解锁模式，使用消息队列，发消息给库存，让他自动解锁
                //3、这样基本没什么消耗
                R r = wareFeignService.orderLockStock(lockVo);

                if(r.getCode() == 0){
                    //3、锁成功了
                    response.setOrder(order.getOrder());
                    //其他服务出异常
//                    int i = 10 / 0;

                    //现在创建订单成功时发布消息到数据库，30分钟没有支付就取消订单
                    //验价成功之后就保存订单信息到了数据库
                    //TODO 订单创建成功，库存那发送锁库存的消息，订单那边发送订单创建成功消息到数据库
                    rabbitTemplate.convertAndSend("order-event-exchange",
                            "order.create.order",
                            order.getOrder());

                    return response;
                }else{
                    //3、锁定商品失败了
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            }else{
                //2、验证价格失败
                response.setCode(2);
                return  response;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {

        //查询这个订单的最新状态,注意，一定要查询最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if(orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单,如果订单还是新建状态没支付，只需要将订单状态变为取消就行
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);

            //同时给库存系统发消息，让库存系统将释放掉这个订单锁定的库存
            try{
                //TODO 保证消息一定发出去,每一个消息都做日志记录，给数据库保存每个消息的详细消息
                //TODO 定期扫描一遍数据将发送失败的消息的重新发送
                //1、网络问题没发出去
                rabbitTemplate.convertAndSend("order-event-exchange",
                        "order.release.other",
                        orderTo);
            }catch (Exception e){
                //TODO 将没发送成功的消息进行重试机制
                //while()
            }
            //再发给MQ一个消息

        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);

        payVo.setSubject(entity.getSkuName());
        payVo.setSubject(entity.getSkuAttrsVals());

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //分页查询
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id"));

        //查询查到的订单的订单项
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);

    }

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public String handlePayResult(PayAsyncVo vo) {

        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){

            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {

        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的详细信息 productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());

        orderItemService.save(orderItemEntity);
    }

    //orderDao是个接口，impl里面包含数据库的基本增删改查方法

    @Autowired
    OrderItemService orderItemService;

    //验价成功保存订单
    private void saveOrder(OrderCreateTo order) {

        //获取订单的基本信息,orderService包括了order orderEntity 的增删改查
        //impl里面包含了订单的增删改查
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        //获取订单项,批量保存
        List<OrderItemEntity> orderItems = order.getOrderItems();
        for (OrderItemEntity orderItem : orderItems) {
            orderItemService.save(orderItem);
        }
        //seata不支持批量保存，seata不支持高并发，只能在低并发的情况下使用
        //orderItemService.saveBatch(orderItems);

    }

    //1.订单提交创建订单
    private OrderCreateTo createOrder(){

        //OrderCreateTo 是最终要提交的，包括整个订单项的信息，订单项目中的商品信息，应付总额和运费
//        private OrderEntity order;     //整个订单项的信息
//        private List<OrderItemEntity> orderItems; //订单项目中的商品信息
//        private BigDecimal payPrice;  //应付总额
//        private BigDecimal fare;     //运费
        //
        OrderCreateTo createTo = new OrderCreateTo();
        //OrderCreateTo 是最终要提交的，包括整个订单项的信息

        //1、创建订单号，订单项的基本信息，运费，地址什么的
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        createTo.setOrder(orderEntity);

        //2、获取订单项的商品信息,有请求头丢失的风险,但是feign的拦截器已经拦截到了当前用户，当前暂时不考虑异步问题
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        createTo.setOrderItems(orderItemEntities);

        //3、再次计算价格,计算价格相关
        computePrice(orderEntity,orderItemEntities);

        return createTo;
    }

    //从后端查到再次计算价格
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //订单总额
        BigDecimal total = new BigDecimal("0.0");

        //总优惠信息
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //总积分和成长值
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        //订单总额
        for (OrderItemEntity entity : orderItemEntities) {

            //单个item的优惠信息
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());

            //单个item总价
            total = total.add(entity.getRealAmount());

            //单个item的积分和成长值
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        orderEntity.setTotalAmount(total);

        //订单应付总额 = 订单总额 + 运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        //总优惠信息
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);

    }


    //封装地址的基本信息，通过传来的地址 addrId 查到
    private OrderEntity buildOrder(String orderSn) {

        //通过LoginUserInterceptor的threadLocal拿到用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());

        //用户确认订单提交来的信息
        //addrId,note,payType,orderToken,payPrice
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();

        //订单号
        orderEntity.setOrderSn(orderSn);

        //根据收获地址查运费 fare中包含收获地址的详细信息和运费，是根据 AddrId 查到的
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {});

        //封装运费和收获人信息
        orderEntity.setFreightAmount(fareResp.getFare());
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());

        //订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //自动确认时间
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    //构建所有订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {

        //直接查询到当前的用户的sku信息，通过getCurrentUserCartItems拿到里面的userId查到
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();

        //直接将cartItem map为 OrderItemEntity
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map( cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                //itemEntity.setIntegrationAmount();
                return itemEntity;
            }).collect(Collectors.toList());

            return  itemEntities;
        }
        return null;
    }

    @Autowired
    ProductFeignService productFeignService;

    //构建一个sku的订单项,包括sku的基本信息，spu的基本信息，查到最新的价格信息
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {

        OrderItemEntity itemEntity = new OrderItemEntity();

        //1、订单信息，
        //2、商品的spu信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo spuInfo = r.getData(new TypeReference<SpuInfoVo>() {});
        itemEntity.setSpuId(spuInfo.getId());
        itemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        itemEntity.setSpuName(spuInfo.getSpuName());
        itemEntity.setCategoryId(spuInfo.getCatalogId());

        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息 不做

        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));

        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal real = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(real);

        return itemEntity;
    }
}